package com.zy.explore.web.constraints.validator;

import com.zy.explore.web.constraints.InNumber;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
public class InNumberValidator implements ConstraintValidator<InNumber, Number> {

    private List<Long> permits;
    private boolean required;

    @Override
    public void initialize(InNumber annotation) {
        permits = Arrays.stream(annotation.value()).boxed().collect(Collectors.toList());
        required = annotation.required();
    }

    @Override
    public boolean isValid(Number number, ConstraintValidatorContext context) {
        context.unwrap(HibernateConstraintValidatorContext.class)
            .addMessageParameter("value", permits.toString());

        if (number == null) {
            return !required;
        }
        return permits.contains(number.longValue());
    }
}
